﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using YunLuPos.SellView;
using YunLuPos.Utils;

namespace YunLuPos.Worker
{
    public class ComWeightWatcher
    {
        SellMainForm form = null;
        SerialPort serialPort = null;
        public bool initWatcher(SellMainForm main)
        {
            this.form = main;

            String port = InIUtil.ReadInIData(InIUtil.WeightSection, InIUtil.W_PORT, "COM1");
            String rate = InIUtil.ReadInIData(InIUtil.WeightSection, InIUtil.W_RATE, "9600");
            String bit = InIUtil.ReadInIData(InIUtil.WeightSection, InIUtil.W_BIT, "8");
            String stopBit = InIUtil.ReadInIData(InIUtil.WeightSection, InIUtil.W_STOPBIT, "1");
            String checkBit = InIUtil.ReadInIData(InIUtil.WeightSection, InIUtil.W_CHECKBIT, "None");

            serialPort = new SerialPort();
            //设置参数
            serialPort.PortName = port;
            serialPort.BaudRate = Int32.Parse(rate); //串行波特率
            serialPort.DataBits = Int32.Parse(bit); //每个字节的标准数据位长度
            serialPort.StopBits = StopBits.One; //设置每个字节的标准停止位数
            if ("1".Equals(stopBit))
            {
                serialPort.StopBits = StopBits.One;
            }
            else if ("1.5".Equals(stopBit))
            {
                serialPort.StopBits = StopBits.OnePointFive;

            }
            else if ("2".Equals(stopBit))
            {
                serialPort.StopBits = StopBits.Two;
            }
            serialPort.Parity = Parity.None; //设置奇偶校验检查协议
            if ("Even".Equals(checkBit))
            {
                serialPort.Parity = Parity.Even;
            }
            else if ("Mark".Equals(checkBit))
            {
                serialPort.Parity = Parity.Mark;
            }
            else if ("Odd".Equals(checkBit))
            {
                serialPort.Parity = Parity.Odd;
            }
            else if ("Space".Equals(checkBit))
            {
                serialPort.Parity = Parity.Space;
            }
            serialPort.ReadTimeout = 3000; //单位毫秒
            serialPort.WriteTimeout = 3000; //单位毫秒
            //串口控件成员变量，字面意思为接收字节阀值，
            //串口对象在收到这样长度的数据之后会触发事件处理函数
            //一般都设为1
            serialPort.ReceivedBytesThreshold = 1;
            serialPort.DataReceived += new SerialDataReceivedEventHandler(CommDataReceived); //设置数据接收事件（监听）

            try
            {
                serialPort.Open(); //打开串口
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
            return true;
        }

        public void CommDataReceived(Object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                Thread.Sleep(300);
                //Comm.BytesToRead中为要读入的字节长度
                int len = serialPort.BytesToRead;

                byte[] readBuffer = new byte[len];
                serialPort.Read(readBuffer, 0, len); //将数据读入缓存
                                                     //处理readBuffer中的数据，自定义处理过程
                List<byte> b = readBuffer.ToList();
                string s = String.Join(" ", b.ConvertAll(a => Convert.ToString(a, 16)));
                Console.WriteLine(s);


                string msg = Encoding.UTF8.GetString(readBuffer, 0, len);
                Console.WriteLine(msg);
                Char[] strs = msg.ToCharArray();
                String str = "";
                foreach (Char c in strs)
                {
                    if (c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9' || c == '0' || c == '.')
                    {
                        str += c;
                    }
                    else if (str != "")
                    {
                        break;
                    }
                }
                if (str != null && !"".Equals(str))
                {
                    Double d = Double.Parse(str.Trim());
                    form.UpdateWeightText(d.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("==================");
                Console.WriteLine(ex);
            }
        }

        public bool stopWatcher()
        {
            serialPort.Close();
            //            outSerialPort.Close();
            return true;
        }


    }
}
